package vip.wangwenhao.item.service.impl;

import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import vip.wangwenhao.common.result.Result;
import vip.wangwenhao.common.util.BeanUtils;
import vip.wangwenhao.item.api.dto.ProductDTO;
import vip.wangwenhao.item.entity.Product;
import vip.wangwenhao.item.mapper.ProductDAO;
import vip.wangwenhao.item.service.ItemService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wwh
 * @date 2019年12月12日 18:06
 */

@Service
@Slf4j
public class ItemServiceImpl implements ItemService {

    @Resource
    private ProductDAO productDAO;

    @Override
    public Result<ProductDTO> queryById(Long id) {
        Product product = productDAO.selectByPrimaryKey(id);
        if (null != product) {
            return Result.success(BeanUtils.copyTo(product, ProductDTO.class));
        }
        return Result.success(null);
    }

    @Override
    public Result<Integer> decrStock(BusinessActionContext businessActionContext, Long id, Integer num) {
        log.warn("decrStock");
        Result<Integer> success = Result.success(productDAO.lockStock(id, num));
        return success;
    }
    @Override
    public Boolean confirmDecrStock(BusinessActionContext businessActionContext) {
        log.warn("confirmDecrStock");
        Long id = Long.valueOf(String.valueOf(businessActionContext.getActionContext("id")));
        Integer num = Integer.valueOf(String.valueOf(businessActionContext.getActionContext("num")));
        int result = productDAO.decrStock(id, num);
        return result == 1;
    }
    @Override
    public Boolean cancelDecrStock(BusinessActionContext businessActionContext) {
        log.warn("cancelDecrStock");
        Long id = Long.valueOf(String.valueOf(businessActionContext.getActionContext("id")));
        Integer num = Integer.valueOf(String.valueOf(businessActionContext.getActionContext("num")));
        int result = productDAO.releaseStock(id, num);
        return result == 1;
    }

    @Override
    public Result<Integer> insert(ProductDTO productDTO) {
        return Result.success( productDAO.insert(BeanUtils.copyTo(productDTO, Product.class)));
    }

    @Override
    public Result<Integer> update(ProductDTO productDTO) {
        return Result.success( productDAO.update(BeanUtils.copyTo(productDTO, Product.class)));
    }

    @Override
    public Result<List<ProductDTO>> query(ProductDTO productDTO) {
        return Result.success(BeanUtils.copyTo(productDAO.query(BeanUtils.copyTo(productDTO, Product.class)), ProductDTO.class));
    }

    @Override
    public Result<Integer> delete(Long id) {
        return Result.success( productDAO.delete(id));
    }
}